import { constantRoutes } from '@/router'
import { getRoutes, findPermissions } from '@/api/sys/menu'
import Layout from '@/layout'

/**
 * 将后台数据转换为组件
 * @param routes asyncRoutes
 */
export function filterAsyncRoutes(routes) {
  return routes.filter(route => {
    if (!route.path) {
      route.path = '/path'
    }
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
        // route.component = () => import('@/views/')
        // route.component = require('@/views/' + route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRoutes(route.children)
    }
    return true
  })
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

const state = {
  routes: [],
  addRoutes: [],
  permissions: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    const roleIds = roles.map((val) => val.id)
    return new Promise(resolve => {
      getRoutes(roleIds).then(res => {
        const accessedRoutes = filterAsyncRoutes(res.data)
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  },
  findPermissions({ commit }, roles) {
    const roleIds = roles.map((val) => val.id)
    return new Promise(resolve => {
      findPermissions(roleIds).then(res => {
        commit('SET_PERMISSIONS', res.data)
        resolve(res.data)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
